package com.clip.action;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.clip.action.util.SessionAttributeKey;
import com.clip.entity.SystemDate;
import com.clip.entity.User;
import com.clip.entity.UserDate;
import com.clip.entity.UserEmail;
import com.clip.entity.Usermobileinfo;
import com.clip.service.SystemDateService;
import com.clip.service.UserDateService;
import com.clip.service.UserEmailService;
import com.clip.service.UserService;
import com.clip.service.UsermobileinfoService;
import com.clip.util.Struts2Utils;
import com.clip.util.ToolsUtils;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Scope("prototype")
public class ControlAction extends ActionSupport{

	private static final long serialVersionUID = 3300414284140534805L;
	
	@Autowired
	private UserService userService;
	@Autowired
	private UserEmailService userEmailService;
	@Autowired 
	private UserDateService userDateService;
	@Autowired 
	private SystemDateService systemDateService;
	@Autowired 
	private UsermobileinfoService usermobileinfoService;
	
	private String nameInput;
	private String sexInput;
	private String birthInput;
	private String qqInput;
	private String msnInput;
	private String mobileInput;
	private String livingInput;
	private String jobInput;
	private String eduInput;
	private String blogInput;
	
	
	private String emailInput;
	private String descInput;
	private String status;
	
	public void getSystemHoliday(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String year = request.getParameter("year");
		year=(year==null||year=="") ? String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) : year;
		Map<String,Object> infoMap=new LinkedHashMap<String,Object>();
		if(year.matches("^[0-9]+$")){
			List<SystemDate> list = systemDateService.getSystemHoliday(Integer.valueOf(year));
			infoMap=systemDateService.orgSystemHolidayList(list);
		}
		Struts2Utils.renderText(ToolsUtils.getJSON(infoMap));
	}
	
	public void getTodayDate(){
		Map<String,Object> infoMap=new LinkedHashMap<String,Object>();
		Calendar today = Calendar.getInstance();
		infoMap.put("year", today.get(Calendar.YEAR));
		infoMap.put("month", today.get(Calendar.MONTH));
		infoMap.put("day", today.get(Calendar.DAY_OF_MONTH));
		Struts2Utils.renderText(ToolsUtils.getJSON(infoMap));
	}
	
	public void getHoliday(){
		HttpServletRequest request = ServletActionContext.getRequest();
		User user = (User) request.getSession().getAttribute(SessionAttributeKey.USER);
		String year = request.getParameter("year");
		year=(year==null||year=="") ? String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) : year;
		Map<String,Object> infoMap=new LinkedHashMap<String,Object>();
		if(year.matches("^[0-9]+$")){

			List<UserDate> list= userDateService.getHoliday(user, Integer.valueOf(year));
			infoMap =userDateService.orgHolidayList(list);
			
		}
		Struts2Utils.renderText(ToolsUtils.getJSON(infoMap));
	}
	/**
	 * 自定义节假日
	 */
	public void setHoliday(){
		String result="{result:'保存成功',flag:0}";
		HttpServletRequest request = ServletActionContext.getRequest();
		boolean Illegal=false;
		String year = request.getParameter("year");
		String holidays = request.getParameter("holidays");
		String regEx="^([1-2]\\d{3})[\\-](0?[0-9]|10|11)[\\-]([1-2]?[0-9]|0[1-9]|30|31)[\\-]([A-Za-z0-9\u4e00-\u9fa5]{1,})[\\-](0|1)";
		String[] holiday = holidays.split("\\|");
		for(String str : holiday){
			if(!str.matches(regEx)){
				Illegal=true;
			}
		}
		if(holidays.equals("nothing")){
			holiday = new String[0];
			Illegal = false;
		}
		if((!Illegal&&year.matches("^[0-9]+$"))){
			User user = (User) request.getSession().getAttribute(SessionAttributeKey.USER);
			userDateService.saveHoliday(user, Integer.valueOf(year), holiday);
		}
		Struts2Utils.renderText(result);
	}
	
	//绑定邮箱修改
	public void saveEmail(){
		String result="{result:'修改失败',flag:0}";
		if(ToolsUtils.searchEmpty(emailInput,descInput,status).size()<=0){
			UserEmail userEmail = userEmailService.getUserEmailByEmail(emailInput);
			if(userEmail!=null){
				result = userEmailService.saveUserEmail(userEmail,descInput,Integer.valueOf(status));
			}
		}
		Struts2Utils.renderText(result);
	}
	//验证绑定邮箱
	public void activite(){
		String result="此链接无效";
		if(ToolsUtils.searchEmpty(status).size()<=0){
			result=userEmailService.activite(status);
		}
		String js="<script>alert('"+result+"');window.location.href='"+ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"';</script>";
		Struts2Utils.renderHtml(js);
	}
	//删除绑定邮箱
	public void deleteEmail(){
		String result="{result:'删除失败',flag:0}";
		if(ToolsUtils.searchEmpty(emailInput).size()<=0){
			HttpSession session=ServletActionContext.getRequest().getSession();
			User user = (User) session.getAttribute(SessionAttributeKey.USER);
			if(!user.getEmail().equals(emailInput)){
				userEmailService.deleteEmail(emailInput,user);
				result="{result:'删除成功',flag:1}";
			}else{
				result="{result:'不能删除'flag:0}";
			}
		}
		Struts2Utils.renderText(result);
	}
	//绑定邮箱并发送邮件
	public void bindEmail(){
		String result="{result:'添加失败'}";
		if(ToolsUtils.searchEmpty(emailInput,descInput).size()<=0&&emailInput.matches("^[a-z0-9_\\.]+@([a-z0-9][a-z0-9]+\\.){1,4}[a-z]{2,3}")){
			HttpSession session=ServletActionContext.getRequest().getSession();
			User user = (User) session.getAttribute(SessionAttributeKey.USER);
			UserEmail userEmail = new UserEmail(user.getId(),emailInput,0,0,ToolsUtils.htmlEnCode(descInput),0);
			result=userEmailService.bindUserEmail(user,userEmail,true);
		}
		Struts2Utils.renderText(result);
	}
	//重新发送验证邮件
	public void resendEmail(){
		String result="{result:'',flag:0}";
		if(ToolsUtils.searchEmpty(emailInput,descInput).size()<=0&&emailInput.matches("^[a-z0-9_\\.]+@([a-z0-9][a-z0-9]+\\.){1,4}[a-z]{2,3}")){
			HttpSession session=ServletActionContext.getRequest().getSession();
			User user = (User) session.getAttribute(SessionAttributeKey.USER);
			result=userEmailService.resendEmail(user,emailInput,descInput);
		}
		Struts2Utils.renderText(result);
	}
	//获得用户所有邮箱（已绑定和未验证）
	public void userEmail(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(SessionAttributeKey.USER);
		Map<String,Object> emailMap = userEmailService.getUserEmail(user.getId());
		Struts2Utils.renderXml(ToolsUtils.getDOM(emailMap));
	}
	//获得用户详细信息
	public void userInfo(){
		String result="{loginflag:0}";
		HttpSession session=ServletActionContext.getRequest().getSession();
		User suser = (User) session.getAttribute(SessionAttributeKey.USER);
		User user = userService.getUserByEmail(suser.getEmail());
		if(user!=null){
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String mobilenum=usermobileinfoService.getBindableMobile(user.getId());
			result="";
			result+="{loginflag:1"
					+",email:'"+user.getEmail()
					+"',name:'"+(user.getName()==null?"":user.getName())
					+"',sex:'"+(user.getSex()==null?"":user.getSex())
					+"',birth:'"+(user.getBirth()==null?"":formatter.format(new Date(user.getBirth())))
					+"',qq:'"+(user.getQq()==null?"":user.getQq())
					+"',msn:'"+(user.getMsn()==null?"":user.getMsn())
					+"',living:'"+(user.getLiving()==null?"":user.getLiving())
					+"',job:'"+(user.getJob()==null?"":user.getJob())
					+"',edu:'"+(user.getEdu()==null?"":user.getEdu())
					+"',blog:'"+(user.getBlog()==null?"":user.getBlog())
					+"',mobilenum:'"+mobilenum+"'}";
		}
		Struts2Utils.renderText(result);
	}
	//修改用户详细信息
	public void saveUserInfo(){
		String result="{flag:0}";
		HttpSession session=ServletActionContext.getRequest().getSession();
		User suser = (User) session.getAttribute(SessionAttributeKey.USER);
		User user = userService.getUserByEmail(suser.getEmail());
		if(user.getUsertype()==2){
			user.setJob(ToolsUtils.htmlEnCode(jobInput));
			user.setBlog(blogInput);
			user = userService.updateUser(user);
			if(user!=null){
				session.setAttribute(SessionAttributeKey.USER, user);
				result="{result:'修改成功！',flag:1}";
			}
			Struts2Utils.renderText(result);
			return;
		}
		
		if(ToolsUtils.searchEmpty(nameInput).size()<=0&&nameInput.matches("^[A-Za-z0-9\u4e00-\u9fa5]{2,20}")){
			user.setName(nameInput);
		}
		if(ToolsUtils.searchEmpty(sexInput).size()<=0&&sexInput.matches("[1|0]")){
			user.setSex(Integer.parseInt(sexInput));
		}
		//birthInput是以2011-1-1-这样的格式传入
		String birthRegex="^([1-2]\\d{3})[\\-](0?[1-9]|10|11|12)[\\-]([1-2]?[0-9]|0[1-9]|30|31)[\\-]$";
		if(ToolsUtils.searchEmpty(birthInput.replaceAll("-", "")).size()<=0&&birthInput.matches(birthRegex)){
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			try {
				user.setBirth(formatter.parse(birthInput).getTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(ToolsUtils.searchEmpty(qqInput).size()<=0&&qqInput.matches("^[1-9][0-9]{4,9}$")){
			user.setQq(qqInput);
		}
		if(ToolsUtils.searchEmpty(msnInput).size()<=0&&msnInput.matches("^[a-z0-9_\\.]+@([a-z0-9][a-z0-9]+\\.){1,4}[a-z]{2,3}")){
			user.setMsn(msnInput);
		}
		if(ToolsUtils.searchEmpty(mobileInput).size()<=0&&mobileInput.matches("^[1][1-9][0-9]\\d{8}$")){
			user.setMobile(Long.parseLong(mobileInput));
		}
		if(ToolsUtils.searchEmpty(livingInput).size()<=0){
			user.setLiving(ToolsUtils.htmlEnCode(livingInput));
		}
		if(ToolsUtils.searchEmpty(jobInput).size()<=0){
			user.setJob(ToolsUtils.htmlEnCode(jobInput));
		}
		if(ToolsUtils.searchEmpty(eduInput).size()<=0){
			user.setEdu(ToolsUtils.htmlEnCode(eduInput));
		}
		if(ToolsUtils.searchEmpty(blogInput).size()<=0&&blogInput.matches("^(http://)+(([0-9a-zA-Z_]+[\\.]+[0-9a-zA-Z_])?([0-9a-zA-Z_]))+[\\.]+([a-zA-Z]{2,3})+.+$")){
			user.setBlog(blogInput);
		}
		//更新
		suser = userService.updateUser(user);
		if(suser!=null){
			session.setAttribute(SessionAttributeKey.USER, suser);
			result="{result:'修改成功！',flag:1}";
		}
		Struts2Utils.renderText(result);
	}
	
	public void updateAvatar(){
		HttpServletRequest request=ToolsUtils.getRequest();
		String imgDada=request.getParameter("imgContent");
		String userID=request.getParameter("userID");
		String xml=ToolsUtils.getDOM(userService.updateAvatar(userID,imgDada));
		userService.checkUserLogo(false,request.getSession());
		Struts2Utils.renderText(xml);
	}
	public void getUpdateAvatorInfo(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		Map returnmap=new HashMap();
		returnmap.put("userID", currentUser.getId());
		returnmap.put("url", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/control/controlAjax!updateAvatar.action");
		HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
		String path="";
		path=apu.get("apacheAvatarPath");
		File file=new File(path+"/"+currentUser.getId()+"/"+currentUser.getId()+"_avatar.jpg");
		if(file.exists()){
			returnmap.put("bigpic", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+"/"+currentUser.getId()+"_avatar.jpg");
			returnmap.put("smallpic", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+apu.get("webAvatarPath")+"/"+currentUser.getId()+"_avatar_small.jpg");
		}else{
			returnmap.put("bigpic", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipbig.jpg");
			returnmap.put("smallpic", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/image/clipsmall.jpg");
			
		}
		this.userService.checkUserLogo(false,session);
		Struts2Utils.renderText(ToolsUtils.getDOM(returnmap));
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getNameInput() {
		return nameInput;
	}

	public void setNameInput(String nameInput) {
		this.nameInput = nameInput;
	}

	public String getSexInput() {
		return sexInput;
	}

	public void setSexInput(String sexInput) {
		this.sexInput = sexInput;
	}

	public String getBirthInput() {
		return birthInput;
	}

	public void setBirthInput(String birthInput) {
		this.birthInput = birthInput;
	}

	public String getQqInput() {
		return qqInput;
	}

	public void setQqInput(String qqInput) {
		this.qqInput = qqInput;
	}

	public String getMsnInput() {
		return msnInput;
	}

	public void setMsnInput(String msnInput) {
		this.msnInput = msnInput;
	}

	public String getMobileInput() {
		return mobileInput;
	}

	public void setMobileInput(String mobileInput) {
		this.mobileInput = mobileInput;
	}
	public String getEmailInput() {
		return emailInput;
	}
	public void setEmailInput(String emailInput) {
		this.emailInput = emailInput;
	}
	public String getDescInput() {
		return descInput;
	}
	public void setDescInput(String descInput) {
		this.descInput = descInput;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}

	public String getLivingInput() {
		return livingInput;
	}

	public void setLivingInput(String livingInput) {
		this.livingInput = livingInput;
	}

	public String getJobInput() {
		return jobInput;
	}

	public void setJobInput(String jobInput) {
		this.jobInput = jobInput;
	}

	public String getEduInput() {
		return eduInput;
	}

	public void setEduInput(String eduInput) {
		this.eduInput = eduInput;
	}

	public String getBlogInput() {
		return blogInput;
	}

	public void setBlogInput(String blogInput) {
		this.blogInput = blogInput;
	}
	
}
